import logging
from .models import MenuModel, PermissionsModel
from django.db.models.signals import post_save
from django.dispatch import receiver

logger = logging.getLogger('erp')

methods = {'POST': '新增', 'GET': '查询', 'PUT': '修改', 'DELETE': '删除', 'PATCH': '局部修改'}


@receiver(post_save, sender=MenuModel)
def create_menus_permissions(sender, instance, created, **kwargs):
    '''
    创建信号监控函数，信号接收者收到之后自动触发，创建菜单资源对应的权限
    '''
    if created:
        logger.info('创建菜单资源对应的权限')
        if isinstance(instance, MenuModel):
            if not instance.parent:  # 因为没有父菜单，那么menu就是功能模块菜单对象
                permission = PermissionsModel.objects.create(name=instance.name + '的权限', is_menu=True)
                permission.menu = instance
                permission.save()
            else:  # 当前菜单访问的是接口
                for method in methods.keys():
                    permission = PermissionsModel.objects.create(name=f'{methods.get(method)}的权限',
                                                                 is_menu=False, method=method, path=instance.url,
                                                                 desc=f'{instance.name}的{methods.get("method")}的权限')
                    permission.menu = instance
                    permission.save()
        else:
            logger.warning('当前对象不是MenuModel类型，所以不需要创建对应的权限')
